<?php
namespace Home\Controller;
use Think\Controller;
use Think\Log;
use Home\Model\woZanPay;
use Exception;
class PublicController extends Controller {
    public function login(){
        if (empty(session('channel_id'))) {exit('error');}
        $user_id = session('user_id');
//        if (empty($user_id)) {
        // 修改成，只要调用这个，就登录。

        import('@.Lib.JoDES');
        $des = new \Des\JoDES();
        $userAuto = cookie('userAuto');
        if(!empty($userAuto)){
            $openid = $des->decode($userAuto,C('GAME_KEY.DES'));
            $info = array(
                'openid'=>$openid,
            );

            $user_info = $this->_register($info);
            session('type','explorer');
            session('openid',$openid);
            session('user_id', $user_info['id']);
            session('user_info', json_encode($user_info));
            $href = I('href', U('Index/index'));
            $href = str_replace('&amp;','&', $href);
            redirect($href); return;
        }

        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            $channel = session('channel_id');
            $name = M('channel')->getField('nick_name');
            $user_id = I('user_id');
            $sign = I('sign');
            if(empty($sign )){
                $href = I('href','');
                if (!empty($href)) {
                    session('_pre_url_', $href);
                }
                $this->display();exit();
            }else{
                $channel_key = D('Channel')->where('id ='.$channel)->getField('appkey');
                $sn = md5($channel.$user_id.$channel_key);
                if($sn != $sign){
                    $this->error('签名错误');
                }

                $openid = md5(md5(C('GAME_KEY.PWD').$channel.$user_id));
                $nickname = I('nick_name')?I('nick_name'):$name.'用户'.$user_id;
                $avatar = I('avatar')?I('avatar'):'';
                $info = array(
                    'openid'=>$openid,
                    'channel_id'=>$channel,
                    'headimgurl'=>$avatar,
                    'nickname'=>$nickname,
                );
                $user_info = $this->_register($info);
                if (!empty($user_info)) {
                    $channel_id = M('Channel')->where(array('id'=>$info['channel_id']))->getField('id');
                    if (empty($channel_id) || $channel_id != $info['channel_id']) {
                        exit('error-k');
                    }
                    session('type','app');
                    session('openid', $info['openid']);
                    session('user_id', $user_info['id']);
                    session('user_info', json_encode($user_info));
                    $href = I('href', U('Index/index'));
                    $href = str_replace('&amp;','&', $href);
                    $href = str_replace('user_id='.$user_id,'user_id=', $href);

                    redirect($href); return;
                } else {
                    exit('user_info error');
                }
            }

        }

        $open_id = I('open_id');
        if(!empty($open_id)){
            $info = array('openid'=>$open_id);

            $user_info = $this->_register($info);
            if (!empty($user_info)) {
                session('type','wx');

                session('openid', $info['openid']);
                session('user_id', $user_info['id']);
                session('user_info', json_encode($user_info));
                $href = I('href', U('Index/index'));
                $href = str_replace('&amp;','&', $href);
                redirect($href); return;
            } else {
                exit('user_info error');
            }
        }

        if (true){
            import('@.Lib.Wx');
            $wx = new \Boo\WX(array('get' => 'userinfo'));
            $info = $wx->getUserInfo();

            if (!empty($info)) {
                $info['channel_id'] = session('channel_id');
                $subscribe = $wx->get_user_info($info['openid']);
                $user_info = $this->_register($info);
                if (!empty($user_info)) {
                    $channel_id = M('Channel')->where(array('id'=>$info['channel_id']))->getField('id');
                    if (empty($channel_id) || $channel_id != $info['channel_id']) {
                        exit('error-k');
                    }
                    session('type','wx');
                    session('openid', $info['openid']);
                    session('user_id', $user_info['id']);
                    session('user_info', json_encode($user_info));
                    $href = I('href', U('Index/index'));
                    $href = str_replace('&amp;','&', $href);
                    redirect($href); return;
                } else {
                    exit('user_info error');
                }
            } else {
                $this->display('Public/wx');exit();
            }
        } else {
            redirect(U('Index/index'));return;
        }
        
    }
    
    public function loginOut(){
        $channel_id = session('channel_id');
        session('user_id',null);
        session('user_info',null);
        cookie('userAuto',null);
        cookie(null);
        session(null);
        redirect(U('Index/index', array('channel'=>$channel_id)));return;
    }
    
    private function _register($info){
        $user_info = array();
        //$map = array('account'=>$info['openid'],'channel_id'=>$info['channel_id'], 'type'=>1);//,




        $Account = D('Account');
        $map = array('account'=>$info['openid'], 'type'=>1);
        $count = $Account->where($map)->count();
        if($count >= 2 ){
            $map = array('account'=>$info['openid'],'channel_id'=>$info['channel_id'], 'type'=>1);
            $one = $Account->where($map)->find();
            if(empty($one)){
                $map = array('account'=>$info['openid'], 'type'=>1);
            }
        }


        $time = getFomartDate();
        $one = $Account->where($map)->find();

        $add_data = array(); // 需要增加渠道数据的集合，里面存type
        $day = getFomartDate(NOW_TIME, 'd+');
        $ChannelData = D('ChannelData');
        $username = $info['username']?$info['username']:'';
        $pwd = $info['pwd']?$info['pwd']:'';
        if (empty($one)) { // 自动注册
            $data = $map; // 因为Map的数据，暂时与data一样，这里简化了
            $data['player_id'] = 0;
            $data['last_login_time'] = $time;
            $data['channel_id'] = $info['channel_id'];
            $data['username'] = $username;
            $data['pwd']=$pwd;
            $account_id = $Account->add($data);
            $data = array(
                'pwd'=>'',
                'tel'=>'',
                'avatar'=>$info['headimgurl'],
                'email'=>'',
                'nick_name'=>$info['nickname'],
                'channel_id' => $info['channel_id'],
                'last_login_ip' => get_client_ip(),
            );
            $player_id = D('Player')->add($data);
            if ($player_id) {
                $user_info = array('id'=>$player_id,'avatar'=>$data['avatar'], 'nick_name'=>$data['nick_name'], 'last_login_time'=>$time, 'add_time'=>$time);
                $data = array('id'=>$account_id,'player_id'=>$player_id);
                $Account->save($data);
            }
            $add_data[] = $ChannelData->TYPE['Reg'];
            $add_data[] = $ChannelData->TYPE['Act'];
            
        } else {  // 已经存在，则属于活跃
            if (empty($one['player_id'])) {
                $data = array(
                    'pwd'=>'',
                    'tel'=>'',
                    'avatar'=>$info['headimgurl'],
                    'email'=>'',
                    'nick_name'=>$info['nickname'],
                    'last_login_ip' => get_client_ip(),
                );
                $player_id = D('Player')->add($data);
                if ($player_id) {
                    $user_info = array('id'=>$player_id,'avatar'=>$data['avatar'], 'nick_name'=>$data['nick_name'], 'last_login_time'=>$time, 'add_time'=>$time);
                    $data = array('id'=>$one['id'],'player_id'=>$player_id);
                    $Account->save($data);
                }
    
                $add_data[] = $ChannelData->TYPE['Reg'];
                $add_data[] = $ChannelData->TYPE['Act'];
            } else {
                $user_info = M('Player')->where(array('id'=>$one['player_id']))->field('id,avatar,nick_name,last_login_time,add_time')->find();
                
                $data = array('id'=>$one['player_id']);
                $data['last_login_time'] = $time;
                $data['last_login_ip'] = get_client_ip();
                D('Player')->save($data);
                
                // 这里判断是否隔天了，
                $tmp = explode(' ',$user_info['last_login_time']);
                if ($day>$tmp[0].' 00:00:00') { // 这里只增加活跃量
                    $add_data[] = $ChannelData->TYPE['Act'];
                }
            }
            $data = array('id'=>$one['id']);
            $data['last_login_time'] = $time;
            $Account->save($data);
        }
        // 增加相应渠道的数据
        if (!empty($add_data)) {
            // 先挨个挨个的判断是否存在记录，不存在就插入
            foreach ($add_data as $item) {
                // 先查出是否有扣量记录
                if (empty($one)){
                    $map = array('channel_id'=>$info['channel_id'],'type'=>$item,'open'=>1);
                }else{
                    $map = array('channel_id'=>$one['channel_id'],'type'=>$item,'open'=>1);
                }

                $kou = M('ChannelKou')->where($map)->find();
                $kou = empty($kou) ? array('bi'=>0,'max_v'=>0) : $kou;


                if (empty($one)){
                    $map = array('channel_id'=>$info['channel_id'], 'day'=>$day, 'type'=>$item);
                }else{
                    $map = array('channel_id'=>$one['channel_id'], 'day'=>$day, 'type'=>$item);
                }
                $map = array('channel_id'=>$info['channel_id'], 'day'=>$day, 'type'=>$item);
                $one = $ChannelData->where($map)->find();
                
                if (empty($one)) {
                    $data = $map;
                    $data['value'] = 1;
                    $data['show_value'] = getKouStep(1,0, $kou['max_v'],$kou['bi']);
                    @$ChannelData->add($data);
                } else {
                    $data = array(
                        'value'=>array('exp','`value` + 1'),
                        'show_value' => array('exp', '`show_value` + '.getKouStep($one['value'],$one['show_value'],$kou['max_v'], $kou['bi']))
                    );
                    @$ChannelData->where(array('id'=>$one['id']))->save($data);
                }
            }
        }
        
        return $user_info;
    }

    public function varify(){
        $config =    array(
            'fontSize'    =>    30,    // 验证码字体大小
            'length'      =>    4,     // 验证码位数
            'useNoise'    =>    false, // 关闭验证码杂点
        );
        $verify = new \Think\Verify($config);
        $verify->entry();
    }

    public function userLogin(){
        $username = I('post.username');
        $pwd = I('post.pwd');
        $is_auto = empty(I('post.is_auto'))?0:1;
        $user = M('account')->where('username = "'.$username.'"')->find();
        if(empty($username) || empty($pwd)) {
            $this->error('用户名或密码不能为空');
        }elseif(!$user){
            $this->error('用户名不存在');
        }elseif(md5(md5(C('GAME_KEY.PWD').$pwd)) != $user['pwd']){
            $this->error('密码错误');
        }
        $info = array(
            'openid'=>$user['account'],

        );
        $user_info = $this->_register($info);
        if($is_auto){
            import('@.Lib.JoDES');
            $des = new \Des\JoDES();
            $openid_des = $des->encode($info['openid'],C('GAME_KEY.DES'));
            cookie('userAuto',$openid_des,array('expire'=>30*24*3600));
        }
        if (!empty($user_info)) {
            session('type','explorer');
            session('openid', $info['openid']);
            session('user_id', $user_info['id']);
            session('user_info', json_encode($user_info));
            $href = I('href', U('Index/index'));
            $href = str_replace('&amp;','&', $href);
            redirect($href); return;
        } else {
            exit('user_info error');
        }
    }

    public function userRegister(){
        $is_auto = empty(I('post.is_auto'))?0:1;
        $username = I('post.username');
        $pwd = I('post.pwd');
        $code = I('post.code');
        $verify = new \Think\Verify();
        if($verify->check($code)){
            $is_user = M('account')->where('username = "'.$username.'"')->count();
            if(empty($username) || empty($pwd)) {
                $this->error('用户名或密码不能为空');
            }elseif($is_user){
                $this->error('用户名已被注册');
            }elseif(strlen($username) > 16 || strlen($username) < 8){
                $this->error('用户名长度必须在8-16位之间');
            }elseif(preg_match("/[\x7f-\xff]/",$username)){
                $this->error('用户名不能含有中文');
            }elseif(strlen($pwd) < 6 || strlen($pwd) > 16){
                $this->error('密码长度必须在6-16位之间');
            }
            $channel = session('channel_id');
            $nickname = $username;
            $openid = md5(md5(C('GAME_KEY.PWD').$channel.$username.$pwd));;
            $info = array(
                'openid'=>$openid,
                'channel_id'=>$channel,
                'headimgurl'=>'',
                'nickname'=>$nickname,
                'username'=>$username,
                'pwd'=>md5(md5(C('GAME_KEY.PWD').$pwd))
            );
            $user_info = $this->_register($info);
            if (!empty($user_info)) {
                $channel_id = M('Channel')->where(array('id'=>$info['channel_id']))->getField('id');
                if (empty($channel_id) || $channel_id != $info['channel_id']) {
                    exit('error-k');
                }
                if($is_auto){
                    import('@.Lib.JoDES');
                    $des = new \Des\JoDES();
                    $openid_des = $des->encode($info['openid'],C('GAME_KEY.DES'));
                    cookie('userAuto',$openid_des,array('expire'=>30*24*3600));
                }
                session('type','explorer');
                session('openid', $info['openid']);
                session('user_id', $user_info['id']);
                session('user_info', json_encode($user_info));
                $href = I('href', U('Index/index'));
                $href = str_replace('&amp;','&', $href);
                redirect($href); return;
            } else {
                exit('user_info error');
            }
        }else{
            $this->error('验证码错误');
        }
    }

    public function notify(){
        $log = print_r($_POST,true);
        
        $data = $_POST;
        $wozan = new woZanPay;
        $sign = md5($data['orderNo'].$data['userName'].$data['result'].$data['amount'].$data['pay_time'].$data['pay_channel'].$wozan->open_key);
        $this->_log($log);
        if($sign == $data['sign']){
            try{
                $trade_no = $data['orderNo'];
                $map = array(
                    'trade_no' => $data['orderNo']
                );
                $table = M('trade');
                $trade = $table->where($map)->find();
                if ($trade['pay_status'] == 1) {
                    Log::record('call back:SUCCESS-2');
                    echo 'success';die;
                }
                $data = array(
                    'callback_charge' => json_encode($data),
                    'pay_status' => 1 // 支付成功状态
                );
                $rst = $table->where($map)->save($data);
                if ($rst) {
                    $game = M('game')->where("id= '".$trade['game_id']."'")->find();
                    $callback_rst = array();
                    $mode = 0;
                    if ($game['gid'] == '10004') { // 空中网回调
                        $callback_rst = notifyKZW($trade,$game);
                        $mode = 1;
                    } else { // 纷至娱乐等统一回调
                        if (!empty($game['reurl'])) { // 只有在回调接口不为空的时候，才进行回调
                            $callback_rst = notifyH5Game($trade, $game);
                        }
                    }
                    if (!empty($callback_rst)) {
                        if(!$callback_rst['result']) { // 回调不成功
                            if (!empty($callback_rst['url'])) { // 回调不成功，并且拼装了参数
                                // 回调未成功。进入Task表，等待处理。
                                $data = array(
                                    'trade_no' =>$trade_no,
                                    'callback_url' => $callback_rst['url'],
                                    'callback_status' => 0,
                                    'callback_time' => date('Y-m-d H:i:s'),
                                    'callback_mode' => $mode
                                );
                                $bool = M('callback_task')->add($data);
                                Log::record('Insert Task:'.$trade_no);
                            }
                        } else { // 回调成功，修改相应状态
                            $data = array(
                                'callback_status' => 1
                            );
                            $table->where($map)->save($data);
                        }
                    }

                    // 分发支付结果给渠道
                    $channel = M('player')->field('channel_id')->where('id='.$trade['player_id'])->find();
                    if (!empty($channel)) {
                        // 查询渠道扣量比例
                        $map = array('channel_id'=>$channel['channel_id'], 'type'=>3, 'open'=>1);  // 这里直接写死为3
                        $kou = M('channel_kou')->where($map)->find();
                        $kou = empty($kou) ? array('max_v'=>0,'bi'=>0) : $kou;

                        $day = date('Y-m-d 00:00:00');
                        $map = array('channel_id'=>$channel['channel_id'], 'type'=>3, 'day'=>$day);
                        $one = M('channel_data')->where($map)->find();
                        if (empty($one)) { // 插入
                            $data = array(
                                'channel_id'=>$channel['channel_id'], 'type'=>3,'day'=>$day,
                                'value' => $trade['pay'],
                                'show_value' => getKouStep(0,0,$kou['max_v'],$kou['bi'], $trade['pay'])
                            );
                            $bool = M('channel_data')->add($data);
                            if (!$bool) {Log::record('Insert Channel data error, TradeId:'.$trade_no);}
                        } else { // 更新
                            $data = array(
                                'value' => array('exp','value+'.$trade['pay']),
                                'show_value' => array('exp', 'show_value+'.getKouStep($one['value'], $one['show_value'], $kou['max_v'],$kou['bi'],$trade['pay']))
                            );
                            $bool = M('channel_data')->where('id='.$one['id'])->save($data);
                            if (!$bool) {Log::record('Update Channel data error, TradeId:'.$trade_no);}
                        }

                    }
                    echo 'success';
                }
                echo 'success';
            }catch(Exception $exception){
                exit($exception->getMessage());
            }
        }else{
            echo 'fail';
        }
    }

    public function pay(){
        $channel_id = I('channel_id');
        $player_id = I('player_id');

        $body = I('paytitle');
        $total_fee = I('pay'); // 支付金额，单位为分
        $game_id = I('_gameID');
        $gparams = $_POST['gparams'];
        $url = I('post.url');
        $url = str_replace('&amp;','&',$url);
        if (empty($body) || !is_numeric($total_fee) || !is_numeric($game_id)) {exit('error');}
        try{
            $tmp = json_decode($gparams, true);
            if (!is_array($tmp)) {exit('error');}
        }catch (Exception $exception) {
            exit('error');
        }
        $time = microtime();
        $trade_no = $channel_id.date("YmdHis").substr($time,2,6);// 商户订单号，生成规则其实随意，唯一就行，
        $trade_type = I('payType');

        try{
            $gmap = array('id'=>$game_id);
            $game_separate = M('game')->where($gmap)->getField('separate');
            $game_separate = empty($game_separate)? '0' : $game_separate;

            $cmap = array('id'=>$channel_id);
            $channel_separate = M('channel')->where($cmap)->getField('separate');
            $channel_separate = empty($channel_separate)? '0' : $channel_separate;

            $tmap = array('status'=>'1');
            $toll = M('toll')->where($tmap)->getField('toll');
            $toll = empty($toll)? '0' : $toll;

            $map = array('channel_id'=>$channel_id, 'type'=>3, 'open'=>1);  // 这里直接写死为3
            $kou = M('channel_kou')->where($map)->find();
            if(empty($kou)){
                $pay_show = $total_fee;
            }else{
                $day = date('Y-m-d 00:00:00');
                $map = array('channel_id'=>$channel_id, 'type'=>3, 'day'=>$day);
                $one =M('channel_data')->where($map)->find();
                if (empty($one)) { // 插入
                    $pay_show = getKouStep(0,0,$kou['max_v'],$kou['bi'],$total_fee);
                } else { // 更新
                    $pay_show = getKouStep($one['value'], $one['show_value'], $kou['max_v'],$kou['bi'],$total_fee);
                }
            }

            $wozan = new woZanPay;
            $wozan->setValue('amount',$total_fee);
            $wozan->setValue('productNo',$wozan->product_no);
            $wozan->setValue('orderNo',$trade_no);
            $wozan->setValue('payType',$trade_type);
            $wozan->setValue('returnurl',$url);
            $wozan->setExt('clientIP',get_client_ip());

            $data = array(
                'trade_no'=>$trade_no,
                'player_id'=>$player_id,
                'pay'=>$total_fee,
                'game_id'=>$game_id,
                'callback_parms' =>$gparams,
                'game_separate'=>$game_separate,
                'channel_separate'=>$channel_separate,
                'toll'=>$toll,
                'pay_show'=>$pay_show
            );


            $bool = M('trade')->add($data);
            if(!$bool){
                exit('网络错误');
            }
            $res = json_decode($wozan->order(),true);
            //$res = $wozan->order();
            $url = $res['url'];
            //$this->ajaxReturn($res);
            if($url){
                $this->ajaxReturn(array('status'=>true,'url'=>$url,'trade_no'=>$trade_no));
            }else{
                $this->ajaxReturn(array('status'=>false,'a'=>$res));
            }
        } catch (Exception $exception) {
            exit($exception->getMessage());
        }


    }


    public function abc(){
        var_dump($_SERVER);die;
    }

    public function H5pay(){
        $obj = I('obj');
        $obj = str_replace('&quot;','"',$obj);

        //$obj = '{"paytitle":"10元宝","pay":100,"gparams":"{\"gid\":\"241\",\"sid\":\"1\",\"channelUid\":\"11604\",\"userid\":\"11604\",\"orderId\":\"201708311404534903631095030169\",\"itemId\":\"30102\"}","_gameID":"118"}';
        $arr = json_decode($obj);
        $obj = str_replace('\\','\\\\',$obj);
        $this->assign('obj',$obj);
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            $is_wx = 0;
        }else{
            $is_wx = 1;
        }
        $this->assign('is_wx',$is_wx);
        $this->display();
    }

    public function pay_status(){
        $trade_no = I('trade_no');
        $status = M('trade')->where('trade_no = "'.$trade_no.'"')->getField('pay_status');
        if($status){
            $this->ajaxReturn(array('status'=>true));
        }else{
            $this->ajaxReturn(array('status'=>false));
        }
    }

    private function _log($data){
        $log_file_path      ='./log/'.date('Y-m-d').'/';
        
        if(!is_dir($log_file_path)){
            mkdir($log_file_path,0777,true);
        }
        $filename = 'orders.log';
        $open = fopen($log_file_path . $filename, 'a');
        fwrite($open,print_r($data,true)."\n");
        fclose($open);
    }

    private function _abnormalOrders($data){
        $log_file_path      ='./abnormal/'.date('Y-m-d').'/';
        
        if(!is_dir($log_file_path)){
            mkdir($log_file_path,0777,true);
        }
        $filename = 'orders.log';
        $open = fopen($log_file_path . $filename, 'a');
        fwrite($open,print_r($data,true)."\n");
        fclose($open);
    }
    

    public function flgPay(){
        $body = empty(I('body'))?'充值':urldecode(I('body'));//订单名称
        $trade_no = I('trade_no','FLG'.date("YmdHis").rand(1000,9999));//订单号
        $pay= I('pay');//充值金额
        $returnurl = urldecode(I('returnurl',''));//跳转地址
        $this->assign('returnurl',$returnurl.'?trade_no='.$trade_no);
        $wx = new \Home\Lib\Wethird\Weixin();
        $openid = $wx->getOpenid();
        if(empty($openid)){//openid为空
        	$this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'openid为空','date'=>date('Y-m-d H:i:s')));
            echo '网络超时';
            header('Location:'.$returnurl);die;
        }
        require_once "./test/WxPay.JsApiPay.php";
        $time_start = date("YmdHis"); // 订单时间
        $time_expire = date("YmdHis", time() + 600); // 订单过期时间，这里为10分钟；
        $notify_url = 'http://flg.h5youx.com/Back/Public/notify'; // 支付成功回调地址
        $trade_type = 'JSAPI'; // 支付方式，JSAPI 支付，
        //②、统一下单
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($pay);
        $input->SetTime_start($time_start);
        $input->SetTime_expire($time_expire);
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type($trade_type);
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);

        if(!array_key_exists("appid", $order)|| !array_key_exists("prepay_id", $order)|| $order['prepay_id'] == "")//参数错误
        {
            $order = \WxPayApi::unifiedOrder($input);
            $data=array('body'=>$body,'out_trade_no'=>$trade_no,'total_fee'=>$pay,'time_start'=>$time_start,'time_expire'=>$time_expire,'notify_url'=>$notify_url,'trade_type'=>$trade_type,'openid'=>$openid);
            if(!array_key_exists("appid", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'appid不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif(!array_key_exists("prepay_id", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif($order['prepay_id'] == ""){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id为空','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }
            
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('wxPay',$jsApiParameters);
        $this->display();
    }

    public function ComicsPay(){
        $body = empty(I('body'))?'充值':urldecode(I('body'));//订单名称
        $trade_no = I('trade_no','Comic'.date("YmdHis").rand(1000,9999));//订单号
        $pay= I('pay');//充值金额
        $returnurl = str_replace('&amp;','&',urldecode(I('returnurl','')));//跳转地址

        $this->assign('returnurl',$returnurl);
        $wx = new \Home\Lib\Wethird\Weixin();
        $openid = $wx->getOpenid();
        if(empty($openid)){//openid为空
            $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'openid为空','date'=>date('Y-m-d H:i:s')));
            echo '网络超时';
            header('Location:'.$returnurl);die;
        }
        require_once "./test/WxPay.JsApiPay.php";
        $time_start = date("YmdHis"); // 订单时间
        $time_expire = date("YmdHis", time() + 600); // 订单过期时间，这里为10分钟；
        $notify_url = 'https://comicadmin.flgwx.com/Back/pay/notifyWeixin'; // 支付成功回调地址
        $trade_type = 'JSAPI'; // 支付方式，JSAPI 支付，
        //②、统一下单
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($pay);
        $input->SetTime_start($time_start);
        $input->SetTime_expire($time_expire);
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type($trade_type);
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);

        if(!array_key_exists("appid", $order)|| !array_key_exists("prepay_id", $order)|| $order['prepay_id'] == "")//参数错误
        {
            $order = \WxPayApi::unifiedOrder($input);
            $data=array('body'=>$body,'out_trade_no'=>$trade_no,'total_fee'=>$pay,'time_start'=>$time_start,'time_expire'=>$time_expire,'notify_url'=>$notify_url,'trade_type'=>$trade_type,'openid'=>$openid);
            if(!array_key_exists("appid", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'appid不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif(!array_key_exists("prepay_id", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif($order['prepay_id'] == ""){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id为空','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('wxPay',$jsApiParameters);
        $this->display();
    }

    public function gmPay(){
        $body = empty(I('body'))?'充值':urldecode(I('body'));//订单名称
        $trade_no = I('trade_no','YYMD'.date("YmdHis").rand(1000,9999));//订单号
        $pay= I('pay');//充值金额
        $returnurl = str_replace('&amp;','&',urldecode(I('returnurl','')));//跳转地址

        $this->assign('returnurl',$returnurl);
        $wx = new \Home\Lib\Wethird\Weixin();
        $openid = $wx->getOpenid();
        if(empty($openid)){//openid为空
            $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'openid为空','date'=>date('Y-m-d H:i:s')));
            echo '网络超时';
            header('Location:'.$returnurl);die;
        }
        require_once "./test/WxPay.JsApiPay.php";
        $time_start = date("YmdHis"); // 订单时间
        $time_expire = date("YmdHis", time() + 600); // 订单过期时间，这里为10分钟；
        $notify_url = 'https://gm.h5youx.com/Back/pay/notifyWeixin'; // 支付成功回调地址
        $trade_type = 'JSAPI'; // 支付方式，JSAPI 支付，
        //②、统一下单
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($pay);
        $input->SetTime_start($time_start);
        $input->SetTime_expire($time_expire);
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type($trade_type);
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);

        if(!array_key_exists("appid", $order)|| !array_key_exists("prepay_id", $order)|| $order['prepay_id'] == "")//参数错误
        {
            $order = \WxPayApi::unifiedOrder($input);
            $data=array('body'=>$body,'out_trade_no'=>$trade_no,'total_fee'=>$pay,'time_start'=>$time_start,'time_expire'=>$time_expire,'notify_url'=>$notify_url,'trade_type'=>$trade_type,'openid'=>$openid);
            if(!array_key_exists("appid", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'appid不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif(!array_key_exists("prepay_id", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif($order['prepay_id'] == ""){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id为空','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('wxPay',$jsApiParameters);
        $this->display();
    }



    public function fuligePay(){
        $body = empty(I('body'))?'充值':urldecode(I('body'));//订单名称
        $trade_no = I('trade_no','FLG'.date("YmdHis").rand(1000,9999));//订单号
        $pay= I('pay');//充值金额
        $returnurl = str_replace('&amp;','&',urldecode(I('returnurl','')));//跳转地址

        $this->assign('returnurl',$returnurl);
        $wx = new \Home\Lib\Wethird\Weixin();
        $openid = $wx->getOpenid();
        if(empty($openid)){//openid为空
            $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'openid为空','date'=>date('Y-m-d H:i:s')));
            echo '网络超时';
            header('Location:'.$returnurl);die;
        }
        require_once "./test/WxPay.JsApiPay.php";
        $time_start = date("YmdHis"); // 订单时间
        $time_expire = date("YmdHis", time() + 600); // 订单过期时间，这里为10分钟；
        $notify_url = 'http://flg.h5youx.com/Back/pay/notifyWeixin'; // 支付成功回调地址
        $trade_type = 'JSAPI'; // 支付方式，JSAPI 支付，
        //②、统一下单
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($pay);
        $input->SetTime_start($time_start);
        $input->SetTime_expire($time_expire);
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type($trade_type);
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);

        if(!array_key_exists("appid", $order)|| !array_key_exists("prepay_id", $order)|| $order['prepay_id'] == "")//参数错误
        {
            $order = \WxPayApi::unifiedOrder($input);
            $data=array('body'=>$body,'out_trade_no'=>$trade_no,'total_fee'=>$pay,'time_start'=>$time_start,'time_expire'=>$time_expire,'notify_url'=>$notify_url,'trade_type'=>$trade_type,'openid'=>$openid);
            if(!array_key_exists("appid", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'appid不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif(!array_key_exists("prepay_id", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif($order['prepay_id'] == ""){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id为空','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('wxPay',$jsApiParameters);
        $this->display();
    }


    public function flgwxPay(){
        $body = empty(I('body'))?'充值':urldecode(I('body'));//订单名称
        $trade_no = I('trade_no','FLGWX'.date("YmdHis").rand(1000,9999));//订单号
        $pay= I('pay');//充值金额
        $returnurl = str_replace('&amp;','&',urldecode(I('returnurl','')));//跳转地址

        $this->assign('returnurl',$returnurl);
        $wx = new \Home\Lib\Wethird\Weixin();
        $openid = $wx->getOpenid();
        if(empty($openid)){//openid为空
            $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'openid为空','date'=>date('Y-m-d H:i:s')));
            echo '网络超时';
            header('Location:'.$returnurl);die;
        }
        require_once "./test/WxPay.JsApiPay.php";
        $time_start = date("YmdHis"); // 订单时间
        $time_expire = date("YmdHis", time() + 600); // 订单过期时间，这里为10分钟；
        $notify_url = 'http://n-backstage.flgwx.com/Back/pay/notifyWeixin'; // 支付成功回调地址
        $trade_type = 'JSAPI'; // 支付方式，JSAPI 支付，
        //②、统一下单
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetOut_trade_no($trade_no);
        $input->SetTotal_fee($pay);
        $input->SetTime_start($time_start);
        $input->SetTime_expire($time_expire);
        $input->SetNotify_url($notify_url);
        $input->SetTrade_type($trade_type);
        $input->SetOpenid($openid);
        $order = \WxPayApi::unifiedOrder($input);

        if(!array_key_exists("appid", $order)|| !array_key_exists("prepay_id", $order)|| $order['prepay_id'] == "")//参数错误
        {
            $order = \WxPayApi::unifiedOrder($input);
            $data=array('body'=>$body,'out_trade_no'=>$trade_no,'total_fee'=>$pay,'time_start'=>$time_start,'time_expire'=>$time_expire,'notify_url'=>$notify_url,'trade_type'=>$trade_type,'openid'=>$openid);
            if(!array_key_exists("appid", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'appid不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif(!array_key_exists("prepay_id", $order)){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id不存在','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }elseif($order['prepay_id'] == ""){
                $this->_abnormalOrders(array('out_trade_no'=>$trade_no,'msg'=>'prepay_id为空','json'=>json_encode($order),'data'=>json_encode($data),'date'=>date('Y-m-d H:i:s')));
                echo '网络超时';
                header('Location:'.$returnurl);die;
            }
        }
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $this->assign('wxPay',$jsApiParameters);
        $this->display();
    }


}